<?php

namespace app\admin\controller;

use app\common\controller\Backend;

class Config extends Backend
{
    public function index()
    {
        $ConfigList = model('Config')->select();

        if($this->request->isPost())
        {
            $params = $this->request->param();

            $list = model('Config')->column('key,id');

            $ConfigData = [];
            
            foreach($params as $key => $item)
            {
                $id = isset($list[$key]) ? $list[$key] : 0;

                $ConfigData[] = [
                    'id' => $id,
                    'value' => $item
                ];
            }

            $idArr = [];

            $files = [];

            if(!empty($_FILES))
            {
                foreach($_FILES as $key => $item)
                {
                    if($_FILES[$key]['error'] != 0 || $_FILES[$key]['size'] <= 0)
                    {
                        continue;
                    }

                    $file = upload($key);

                    $files[] = $file;

                    if($file)
                    {
                        $id = isset($list[$key]) ? $list[$key] : 0;

                        if($id)
                        {
                            $idArr[] = $id;

                            $ConfigData[] = [
                                'id' => $id,
                                'value' => $file['data'],
                            ];
                        }
                    }

                }
            }
            $ConfigThumbs = model('Config')->whereIn('id',$idArr)->select();

            // /uploads/20220531/1d29e12eb1c71c1d6072b57664504baa.jpg
            // /uploads/20220531/002a288a93df0412ef169cb5a042388e.jpg
            // halt($ConfigThumbs);
            // $ConfigData = !empty($ConfigThumbs) ? $ConfigThumbs : [];

            $result = model('Config')->isUpdate(true)->saveAll($ConfigData);

            if($result === FALSE)
            {
                if(!empty($_FILES) && !empty($files))
                {
                    foreach($files as $item)
                    {
                        @is_file('.'.$item['data']) && @unlink('.'.$item['data']);
                    }
                }
                $this->error(model('Config')->getError());
            }else{

                if(!empty($_FILES) && !empty($ConfigThumbs))
                {
                    // halt($ConfigThumbs);
                    foreach($ConfigThumbs as $item)
                    {
                        @is_file('.'.$item['value']) && @unlink('.'.$item['value']);
                    }
                }

                $this->success('更新网站配置成功',url('admin/config/index'));
            }


        }

        return $this->fetch('',[
            'ConfigList' => $ConfigList
        ]);
    }
}
